<?php

/**
 * 英孚海外留学
 * Class EfAction
 * @author jie
 * 2017-10-20
 */

define('TESTURL', 'https://stg-efcom-lb.eflangtech.com/secureformsapi/brochuresubmission');
define('URL', 'https://services.ef.com/secureformsapi/brochuresubmission');

define('TESTCAMPAIGNURL', 'https://stg-efcom-lb.eflangtech.com/secureformsapi/CampaignSubmission');
define('CAMPAIGNURL', 'https://services.ef.com/secureformsapi/CampaignSubmission');


class EfAction extends Action
{
    /**
     * @param $orderInfo     /订单数据
     * @return bool
     */
    public function synchroOrder($orderInfo)
    {
        $sql = 'select `openid`,`unionid` from wx_'.$orderInfo['fromCustomerId'].'_user_weixin_info where userId="'.$orderInfo['uId'].'"';
        $userInfo = M()->query($sql);
        $bool = true;
        $postUrl = $synchroRet = $syncOrderSn = '';
        if($orderInfo['authConfig']){
            $authConfig = json_decode($orderInfo['authConfig'], true);
            $postUrl = $authConfig['synchroUrl'];
        }

        foreach($orderInfo['proList'] as $k=>$v){
            $post_data = [];
            $customInfo = json_decode($v['customizedInfo'], true);
            $post_data['customer']['FirstName'] = '';
            $post_data['customer']['LastName'] = '';
            $post_data['customer']['MobilePhone'] = '';
            $post_data['customer']['Email'] = '';
            $post_data['customer']['DateOfBirth'] = '';
            $post_data['customer']['StateRegionName'] = '';
            $post_data['customer']['City'] = '';
            $post_data['customer']['StateRegionCode'] = '';
            //用户信息
            foreach($customInfo as $key=>$val){
                //$val['name']需要和运营协商定死,如果单方面改动会导致失败
                switch($val['name']){
                    case  '姓名':    //姓名
                        $firstName = mb_substr($val['description'], 1,(mb_strlen($val['description'],'utf-8')-1),'utf-8');
                        $lastName = mb_substr($val['description'],0,1,'utf-8');
                        $post_data['customer']['FirstName'] = $firstName?$firstName:$lastName;
                        $post_data['customer']['LastName'] = $lastName?$lastName:'';
                        break;
                    case  '手机号码':    //手机
                        $post_data['customer']['MobilePhone'] = $val['description'];
                    break;
                    case  '邮箱':    //邮件
                        $post_data['customer']['Email'] = $val['description'];
                        break;
                    case  '生日':    //生日
                        $post_data['customer']['DateOfBirth'] = $val['description'];
                        break;
                    case  '地址':    //地区
                        $areaInfo = self::getProvinceCode($val["other"]['province']);
                        $post_data['customer']['StateRegionCode'] = $areaInfo[0];
                        if($val["other"]['province']){
                            $post_data['customer']['StateRegionName'] = $areaInfo[1];
                        }
                        if($val["other"]['city']){
                            if(strpos($val["other"]['city'], '市') || strpos($val["other"]['city'], '区')){
                                $val["other"]['city'] = mb_substr($val["other"]['city'], 0, (mb_strlen($val["other"]['city'], 'utf-8')-1), 'utf-8');
                            }
                            $post_data['customer']['City'] = $val["other"]['city'];
                        }
                        break;
                    default:
                        break;
                }

            }

            $comments = '商品名称:'.$v['name'].'|价格:'.$v['price'].'元';
            if($orderInfo['refereePhone']){
                $comments = '商品名称:'.$v['name'].'|价格:'.$v['price'].'元|推荐人手机:'.$orderInfo['refereePhone'];
            }
            if($orderInfo['isTeam']){
                $comments = '商品名称:'.$v['name'].'|价格:'.$v['price'].'元|推荐人手机:'.$orderInfo['refereePhone'].'|发起人手机:'.$orderInfo['teamFirstPhone'].'|详情:'.$orderInfo['teamInfo'];
            }

            $post_data['customer']['Comments'] = $comments;    //商品名称:新加坡游学|价格:1000元
            $post_data['customer']['CountryCode'] = "CN";
            $post_data['customer']['HomePhone'] = "";
            $post_data['customer']['AddressLine1'] = "";
            $post_data['customer']['AddressLine2'] = "";
            $post_data['customer']['AddressLine3'] = "";
            $post_data['customer']['PostalCode'] = "";
            $post_data['customer']['CountryOfResidence'] = "CN";
            //$post_data['customer']['Gender'] = "";
            $post_data['customer']['ParentsFirstName'] = "";
            $post_data['customer']['ParentsLastName'] = "";
            $post_data['customer']['ParentsEmail'] = "";
            $post_data['customer']['ParentsPhoneNo'] = "";
            $eTag = $programCode = '';
            //处理ETag和programCode
            if($v['category']){
                $category = explode(',', $v['category']);
                foreach($category as $key=>$val){
                    if(strpos($val, "ETag") === 0){
                        $eTag .= $val;
                    }

                    if(strpos($val, 'ProgramCode') === 0){
                        $programCode .= $val;
                    }
                }
                //给EF传的ETag/ProgramCode也需要和运营协商固定
                $eTag = trim(str_replace('ETag:', ',', $eTag), ',');
                $programCode = trim(str_replace('ProgramCode:', ',', $programCode), ',');
            }
            $post_data['extendedDetail']['WantsBrochure'] = 'TRUE';
            $post_data['extendedDetail']['WantsMoreInfo'] = 'TRUE';
            $post_data['extendedDetail']['ProgramCode'] = $programCode;
            $post_data['extendedDetail']['ProductCode'] = '';
            $post_data['extendedDetail']['EFComMarketCode'] = 'cn';
            $post_data['extendedDetail']['EnqFormType'] = 'BRO';
            $post_data['extendedDetail']['EnqFormId'] = 'AutomationTool';
            $post_data['extendedDetail']['IsExpressCall'] = false;

            $post_data['weChat']['WeChatID'] = $userInfo[0]['openid']?$userInfo[0]['openid']:'';
            $post_data['weChat']['WeChatUnionID'] = $userInfo[0]['unionid']?$userInfo[0]['unionid']:'';

            //$post_data['tracking']['CountryOfResidence'] = 'CN';
            if($orderInfo['saleSource']){
                $post_data['tracking']['EntrySourceCode'] = '014808';
            }else{
                $post_data['tracking']['EntrySourceCode'] = '0071048';
            }

            $post_data['tracking']['FormUrl'] = '';
            $post_data['tracking']['ReferringUrl'] = '';
            $post_data['tracking']['PartnerCode'] = 'WeiXin';
            $post_data['tracking']['Keywords'] = 'wechat';
            //分享的单独标记
            if($v['miUid']){
                $post_data['tracking']['EntrySourceCode'] = '014808';
            }

            if(self::getSourceCode($orderInfo['saleFullName'])){
                $post_data['tracking']['EntrySourceCode'] = '00505';
            }

            if(!empty($eTag) && $v['price'] >= 100){
                $eTag = $eTag.'_RES';
            }else if(empty($eTag) && $v['price']>=100){
                $eTag = 'RES';
            }

            if($orderInfo['saleSource']){
                $eTag = 'REF_'.str_replace( ' ', '-',$orderInfo['saleFullName']).'_'.$eTag;
            }

            if($orderInfo['isTeam']){
                $eTag = $eTag.'_TG';
            }

            $post_data['tracking']['Etag'] = $eTag;
            $post_data = json_encode($post_data, JSON_UNESCAPED_UNICODE);

            $cid = $_GET['customerId'];
            if($cid){
                $sql = "insert into `wx_".$cid."_log` (`cid`,`module`,`op`,`content`,`createTime`) values (".$cid.",'mallOrder','update','".$post_data."','".date('Y-m-d H:i:s')."')";
                M()->execute($sql);
            }

            $form_submit_url = $postUrl?$postUrl:TESTURL;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            $agent =  "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
            curl_setopt($ch, CURLOPT_USERAGENT, $agent);
            curl_setopt($ch, CURLOPT_URL, $form_submit_url );
            curl_setopt($ch, CURLOPT_TIMEOUT, 0 );
            curl_setopt($ch, CURLOPT_POST, 1 );
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            $postResult = curl_exec($ch);
            $repStr= ["'"=>''];
            $errorStr = strtr(curl_error($ch), $repStr);
            $synchroRet .= 'productId:'.$v['id'].',code:'.curl_getinfo($ch, CURLINFO_HTTP_CODE).',error:'.$errorStr.',ret:'.$postResult.',';
            $postResult = json_decode($postResult, true);
            $syncOrderSn .= $postResult['FormId'].',';
            if($postResult['FormId'] == 0 || curl_getinfo($ch,CURLINFO_HTTP_CODE) !==200)
            {
                $bool = false;
                Log::write('jie----post_data-fail:'.print_r($post_data, true));
            }
            curl_close($ch);
        }
        $synchroRet = trim($synchroRet, ',');
        $syncOrderSn = trim($syncOrderSn, ',');
        return [
            'synchroRet'=>$synchroRet,
            'order_sn'=>$syncOrderSn,
            'bool'=>$bool
        ];
    }

    /**
     * 同步好友信息到英孚crm
     * @param $data /注册好友信息
     * @return array
     */
    public function synchroFriends($data){
        $post_data = [];
        $lastName = $firstName = $synchroRet = $syncOrderSn = '';
        $bool = true;
        if($data['fullName']){
            $firstName = mb_substr($data['fullName'], 1,(mb_strlen($data['fullName'],'utf-8')-1),'utf-8');
            $lastName = mb_substr($data['fullName'],0,1,'utf-8');
        }

        $post_data['customer']['FirstName'] = $firstName?$firstName:$lastName;
        $post_data['customer']['LastName'] = $lastName;
        $post_data['customer']['MobilePhone'] = $data['phone'];
        $post_data['customer']['HomePhone'] = '';
        $post_data['customer']['Email'] = $data['email'];
        $post_data['customer']['DateOfBirth'] = $data['birthday']?$data['birthday']:'';
        $post_data['customer']['AddressLine1'] = "";
        $post_data['customer']['AddressLine2'] = "";
        $post_data['customer']['AddressLine3'] = "";
        $post_data['customer']['PostalCode'] = "";

        $areaInfo = self::getProvinceCode($data["province"]);
        $post_data['customer']['StateRegionName'] = $areaInfo[1]?$areaInfo[1]:'';
        $post_data['customer']['StateRegionCode'] = $areaInfo[0]?$areaInfo[0]:$areaInfo[0];     //需要再次转换
        if($data['city']){
            if(strpos($data['city'], '市') || strpos($data['city'], '区')){
                $data['city'] = mb_substr($data['city'], 0, (mb_strlen($data['city'], 'utf-8')-1), 'utf-8');
            }
            $post_data['customer']['City'] = $data['city']?$data['city']:'';
        }
        $post_data['customer']['CountryOfResidence'] = "CN";
        $post_data['customer']['CountryCode'] = "CN";
        //$post_data['customer']['Gender'] = $data['gender'];
        $post_data['customer']['Comments'] = $data['refereePhone'];
        if($data['type'] == 'form'){
            $post_data['customer']['Comments'] = '文章标题:'.$data['articleName'].'|推荐人手机:'.$data['refereePhone'];
        }
        $post_data['customer']['ParentsFirstName'] = "";
        $post_data['customer']['ParentsLastName'] = "";
        $post_data['customer']['ParentsEmail'] = "";
        $post_data['customer']['ParentsPhoneNo'] = "";

        $post_data['extendedDetail']['EFComMarketCode'] = 'cn';
        $post_data['extendedDetail']['WantsBrochure'] = 'TRUE';
        $post_data['extendedDetail']['WantsMoreInfo'] = 'TRUE';
        $post_data['extendedDetail']['IsGroup'] = 'FALSE';

        $post_data['tracking']['FormUrl'] = '';
        $post_data['tracking']['ReferringUrl'] = '';
        $post_data['tracking']['PartnerCode'] = 'WeiXin';

        if($data['type'] == 'form'){
            $post_data['tracking']['Etag'] = 'REF_'.str_replace( ' ', '-',$data['saleFullName']).'_YXQArticle';
        }else{
            $post_data['tracking']['Etag'] = 'REF_'.str_replace( ' ', '-',$data['saleFullName']).'_YXQ';
        }
        $post_data['tracking']['EntrySourceCode'] = '014808';

        if(self::getSourceCode($data['saleFullName'])){
            $post_data['tracking']['EntrySourceCode'] = '00505';
        }

        $post_data['tracking']['Keywords'] = 'wechat';
        if($data['type'] == 'form'){
            $post_data['campaignData']['CampaignName'] = $data['CampaignName'];
        }else{
            $post_data['campaignData']['CampaignName'] = $data['CampaignName']?$data['CampaignName']:'EF Circle';
        }
        $post_data['campaignData']['CampaignAllocationPrograms'] = $data['CampaignAllocationProgram'];  //excel上CampaignAllocationProgram不带s
        $post_data['campaignData']['CampaignAllocationCode'] = trim($data['CampaignAllocationCode']);
        $post_data['campaignData']['CampaignQuestionAnswer'] = [];

        $post_data['weChat']['WeChatID'] = $data['openid'];
        $post_data['weChat']['WeChatUnionID'] = $data['unionid'];

        $post_data = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $cid = $_GET['customerId'];
        if($cid){
            $sql = "insert into `wx_".$cid."_log` (`cid`,`module`,`op`,`content`,`createTime`) values (".$cid.",'friendsOrder','add','".$post_data."','".date('Y-m-d H:i:s')."')";
            M()->execute($sql);
        }

        $length = strripos($data['synchroUrl'], '/');
        $synchroUrl = substr($data['synchroUrl'],0,$length);
        $postUrl = $synchroUrl.'/CampaignSubmission';
        $form_submit_url = $synchroUrl?$postUrl:TESTCAMPAIGNURL;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);   //由于没有配置信任的服务器HTTPS验证,跳过ssl验证
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        $agent =  "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
        curl_setopt($ch, CURLOPT_USERAGENT, $agent);
        curl_setopt($ch, CURLOPT_URL, $form_submit_url );
        curl_setopt($ch, CURLOPT_TIMEOUT, 0 );
        curl_setopt($ch, CURLOPT_POST, 1 );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        $postResult = curl_exec($ch);
        $repStr= ["'"=>''];
        $errorStr = strtr(curl_error($ch), $repStr);
        $synchroRet = 'uid:'.$data['id'].',code:'.curl_getinfo($ch, CURLINFO_HTTP_CODE).',error:'.$errorStr.',ret:'.$postResult;
        $postResult = json_decode($postResult, true);
        $syncOrderSn = $postResult['FormId'];
        if($postResult['FormId'] == 0 || curl_getinfo($ch,CURLINFO_HTTP_CODE) !==200)
        {
            $bool = false;
            Log::write('jie----post_data-fail:'.$synchroUrl.'|postUrl:'.$postUrl);
        }
        curl_close($ch);
        return [
            'synchroRet'=>$synchroRet,
            'order_sn'=>$syncOrderSn,
            'bool'=>$bool
        ];
    }

    /**
     * 获取对应的省份编码
     * @param $province /省份名称
     * @return string||null
     */
    protected function getProvinceCode($province){
        $code = '';
        switch($province){
            case '北京市':
                $code = '11';
                $province = '北京';
                break;
            case '北京':
                $code = '11';
                $province = '北京';
                break;
            case '天津市':
                $code = '12';
                $province = '天津';
                break;
            case '天津':
                $code = '12';
                $province = '天津';
                break;
            case '河北省':
                $code = '13';
                $province = '河北';
                break;
            case '河北':
                $code = '13';
                $province = '河北';
                break;
            case '山西省':
                $code = '14';
                $province = '山西';
                break;
            case '山西':
                $code = '14';
                $province = '山西';
                break;
            case '内蒙古自治区':
                $code = '15';
                $province = '内蒙古';
                break;
            case '内蒙古':
                $code = '15';
                $province = '内蒙古';
                break;
            case '辽宁省':
                $code = '21';
                $province = '辽宁';
                break;
            case '辽宁':
                $code = '21';
                $province = '辽宁';
                break;
            case '吉林省':
                $code = '22';
                $province = '吉林';
                break;
            case '吉林':
                $code = '22';
                $province = '吉林';
                break;
            case '黑龙江省':
                $code = '23';
                $province = '黑龙江';
                break;
            case '黑龙江':
                $code = '23';
                $province = '黑龙江';
                break;
            case '上海市':
                $code = '31';
                $province = '上海';
                break;
            case '上海':
                $code = '31';
                $province = '上海';
                break;
            case '江苏省':
                $code = '32';
                $province = '江苏';
                break;
            case '江苏':
                $code = '32';
                $province = '江苏';
                break;
            case '浙江省':
                $code = '33';
                $province = '浙江';
                break;
            case '浙江':
                $code = '33';
                $province = '浙江';
                break;
            case '安徽省':
                $code = '34';
                $province = '安徽';
                break;
            case '安徽':
                $code = '34';
                $province = '安徽';
                break;
            case '福建省':
                $code = '35';
                $province = '福建';
                break;
            case '福建':
                $code = '35';
                $province = '福建';
                break;
            case '江西省':
                $code = '36';
                $province = '江西';
                break;
            case '江西':
                $code = '36';
                $province = '江西';
                break;
            case '山东省':
                $code = '37';
                $province = '山东';
                break;
            case '山东':
                $code = '37';
                $province = '山东';
                break;
            case '河南省':
                $code = '41';
                $province = '河南';
                break;
            case '河南':
                $code = '41';
                $province = '河南';
                break;
            case '湖北省':
                $code = '42';
                $province = '湖北';
                break;
            case '湖北':
                $code = '42';
                $province = '湖北';
                break;
            case '湖南省':
                $code = '43';
                $province = '湖南';
                break;
            case '湖南':
                $code = '43';
                $province = '湖南';
                break;
            case '广东':
                $code = '44';
                $province = '广东';
                break;
            case '广东省':
                $code = '44';
                $province = '广东';
                break;
            case '广西壮族自治区':
                $code = '45';
                $province = '广西';
                break;
            case '广西':
                $code = '45';
                $province = '广西';
                break;
            case '海南省':
                $code = '46';
                $province = '海南';
                break;
            case '海南':
                $code = '46';
                $province = '海南';
                break;
            case '重庆市':
                $code = '50';
                $province = '重庆';
                break;
            case '重庆':
                $code = '50';
                $province = '重庆';
                break;
            case '四川省':
                $code = '51';
                $province = '四川';
                break;
            case '四川':
                $code = '51';
                $province = '四川';
                break;
            case '贵州省':
                $code = '52';
                $province = '贵州';
                break;
            case '贵州':
                $code = '52';
                $province = '贵州';
                break;
            case '云南省':
                $code = '53';
                $province = '云南';
                break;
            case '云南':
                $code = '53';
                $province = '云南';
                break;
            case '西藏自治区':
                $code = '54';
                $province = '西藏';
                break;
            case '西藏':
                $code = '54';
                $province = '西藏';
                break;
            case '陕西省':
                $code = '61';
                $province = '陕西';
                break;
            case '陕西':
                $code = '61';
                $province = '陕西';
                break;
            case '甘肃省':
                $code = '62';
                $province = '甘肃';
                break;
            case '甘肃':
                $code = '62';
                $province = '甘肃';
                break;
            case '青海省':
                $code = '63';
                $province = '青海';
                break;
            case '青海':
                $code = '63';
                $province = '青海';
                break;
            case '宁夏回族自治区':
                $code = '64';
                $province = '宁夏';
                break;
            case '宁夏':
                $code = '64';
                $province = '宁夏';
                break;
            case '新疆维吾尔自治区':
                $code = '65';
                $province = '新疆';
                break;
            case '新疆':
                $code = '65';
                $province = '新疆';
                break;
            case '台湾省':
                $code = '71';
                $province = '台湾';
                break;
            case '台湾':
                $code = '71';
                $province = '台湾';
                break;
            case '香港特别行政区':
                $code = '91';
                $province = '香港';
                break;
            case '香港':
                $code = '91';
                $province = '香港';
                break;
            case '澳门特别行政区':
                $code = '92';
                $province = '澳门';
                break;
            case '澳门':
                $code = '92';
                $province = '澳门';
                break;
            default:
                break;
        }
        return [$code,$province];
    }

    /**
     * 获取特殊销售的资源码
     * @param $saleFullName /销售名字
     * @return bool
     */
    public function getSourceCode($saleFullName){
        $specialSaleArr = [
            'Marrisa Xiao',
            'Vivi Gao',
            'Luddy Liu',
            'Adam He',
            'Doris Han',
            'Eric Liang',
            'Delia Peng',
            'Rebecca Cao',
            'Sherry Ding'
        ];
        if(in_array(trim($saleFullName), $specialSaleArr)){
            return true;
        }else{
            return false;
        }
    }
}